<template>
  <div class="user-management">
    <el-card>
      <div slot="header" class="page-header">
        <h2>用户管理</h2>
        <div class="header-actions">
          <el-input 
            v-model="searchQuery" 
            placeholder="搜索用户名或姓名" 
            clearable
            style="width: 200px; margin-right: 10px;"
            @clear="handleSearch"
            @keyup.enter.native="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
          </el-input>
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 添加用户
          </el-button>
          <el-button type="warning" @click="handleLogout">
            <i class="el-icon-switch-button"></i> 退出登录
          </el-button>
        </div>
      </div>
      
      <el-table 
        :data="users" 
        border 
        stripe 
        :loading="loading"
        style="width: 100%; margin-top: 10px;"
      >
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名" width="150"></el-table-column>
        <el-table-column prop="name" label="姓名" width="150"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="150"></el-table-column>
        <el-table-column 
          prop="role" 
          label="角色" 
          width="120"
          :formatter="formatRole"
        ></el-table-column>
        <el-table-column 
          prop="status" 
          label="状态" 
          width="120"
        >
          <template slot-scope="scope">
            <el-switch 
              v-model="scope.row.status" 
              active-value="1" 
              inactive-value="0"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column 
          prop="createTime" 
          label="创建时间" 
          width="180"
          :formatter="formatDate"
        ></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              type="primary" 
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              size="mini" 
              type="danger" 
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 用户表单对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="userForm" 
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option 
              v-for="role in roles" 
              :key="role.value" 
              :label="role.label" 
              :value="role.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getUserList, 
  addUser, 
  updateUser, 
  deleteUser, 
  updateUserStatus 
} from '@/api/user'

export default {
  name: 'UserManagement',
  data() {
    return {
      users: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      loading: false,
      searchQuery: '',
      dialogVisible: false,
      dialogTitle: '添加用户',
      form: {
        id: null,
        username: '',
        name: '',
        email: '',
        phone: '',
        status: 1,
        role: 'user'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
        ]
      },
      roles: [
        { label: '管理员', value: 'admin' },
        { label: '普通用户', value: 'user' }
      ]
    }
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      this.loading = true
      try {
        const response = await getUserList({
          page: this.currentPage,
          size: this.pageSize,
          keyword: this.searchQuery
        })
        this.users = response.data.records
        this.total = response.data.total
      } catch (error) {
        this.$message.error('获取用户列表失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    
    // 格式化角色显示
    formatRole(row) {
      const role = this.roles.find(r => r.value === row.role)
      return role ? role.label : row.role
    },
    
    // 格式化日期显示
    formatDate(row) {
      return row.createTime
    },
    
    // 搜索用户
    handleSearch() {
      this.currentPage = 1
      this.getUserList()
    },
    
    // 处理添加用户
    handleAdd() {
      this.dialogTitle = '添加用户'
      this.form = {
        id: null,
        username: '',
        name: '',
        email: '',
        phone: '',
        status: 1,
        role: 'user'
      }
      this.dialogVisible = true
    },
    
    // 处理编辑用户
    handleEdit(row) {
      this.dialogTitle = '编辑用户'
      this.form = { ...row }
      this.dialogVisible = true
    },
    
    // 处理删除用户
    async handleDelete(id) {
      try {
        await this.$confirm('确定要删除该用户吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await deleteUser(id)
        this.$message.success('删除成功')
        this.getUserList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
          console.error(error)
        }
      }
    },
    
    // 处理状态变更
    async handleStatusChange(row) {
      try {
        await updateUserStatus(row.id, row.status)
        this.$message.success(`用户状态已${row.status === 1 ? '启用' : '禁用'}`)
      } catch (error) {
        // 失败时恢复原状态
        row.status = row.status === 1 ? 0 : 1
        this.$message.error('更新状态失败')
        console.error(error)
      }
    },
    
    // 提交表单
    async handleSubmit() {
      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.form.id) {
              // 编辑操作
              await updateUser(this.form)
              this.$message.success('更新成功')
            } else {
              // 添加操作
              await addUser(this.form)
              this.$message.success('添加成功')
            }
            this.dialogVisible = false
            this.getUserList()
          } catch (error) {
            this.$message.error(this.form.id ? '更新失败' : '添加失败')
            console.error(error)
          }
        }
      })
    },
    
    // 处理分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
      this.getUserList()
    },
    
    // 处理当前页变化
    handleCurrentChange(val) {
      this.currentPage = val
      this.getUserList()
    },
    
    // 退出登录
    handleLogout() {
      this.$confirm('确定要退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        localStorage.removeItem('token')
        this.$router.push('/login')
        this.$message.success('已退出登录')
      }).catch(() => {
        // 取消退出
      })
    }
  },
  mounted() {
    this.getUserList()
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
